/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.swagger2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;

@Configuration
@ConditionalOnProperty(name = "doll.swagger2.enabled", havingValue = "true", matchIfMissing = true)
@Import({ DollSwagger2Porperties.class, Swagger2DocumentationConfiguration.class })
public class DollSwagger2AutoConfig {

	/** Spring应用名 */
	public static final String SPRING_APPLICATION_NAME = "spring.application.name";

	@Autowired
	private DollSwagger2Porperties dsProperties;

	@Autowired
	private Environment env;

	/**
	 * 默认Docket对象
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean(Docket.class)
	public Docket defaultDocket() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(defaultApiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage(dsProperties.getBasePackage())).paths(PathSelectors.any())
				.build();
	}

	/**
	 * 默认API文档信息
	 * @return
	 */
	private ApiInfo defaultApiInfo() {
		String appName = env.getProperty(SPRING_APPLICATION_NAME);
		appName = (!StringUtils.hasText(appName) ? "" : appName.toUpperCase());

		String title = dsProperties.getTitle();
		if (!StringUtils.hasText(title) || DollSwagger2Porperties.DEFAULT_TITLE.equals(dsProperties.getTitle())) {
			title = appName + " " + dsProperties.getTitle();
		}

		String author = dsProperties.getAuthor();
		if (!StringUtils.hasText(author) && StringUtils.hasText(appName)) {
			author = appName + " Group™";
		}

		Contact contact = new Contact(author, dsProperties.getUrl(), dsProperties.getEmail());
		return new ApiInfoBuilder().license(dsProperties.getLicense()).licenseUrl(dsProperties.getLicenseUrl())
				.title(title).termsOfServiceUrl(dsProperties.getTermsOfServiceUrl())
				.description(dsProperties.getDescription()).contact(contact).version(dsProperties.getVersion()).build();
	}
}
